package com.duleme.servlet;

import com.duleme.common.EncodeUtils;
import com.duleme.common.JsonUtils;
import com.duleme.dao.BookDao;
import com.duleme.entity.Book;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

//卖家后台修改书籍的价格和库存数量
@WebServlet("/update/book")
public class BookUpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        EncodeUtils.setEncoding(req, resp);
        String method = req.getParameter("method");
        if (method.equals("modify")) {
            int bookId = Integer.parseInt(req.getParameter("bookId"));
            int remain = Integer.parseInt(req.getParameter("remain"));
            double price = Double.parseDouble(req.getParameter("price"));
            BookDao dao = new BookDao();
            if (dao.updateBookRemain(bookId, price, remain)) {
                resp.getWriter().print(JsonUtils.result2Json("1"));
            } else
                resp.getWriter().print(JsonUtils.result2Json("0"));

        }
        if (method.equals("delete")) {
            int shopId=Integer.parseInt(req.getParameter("shopId"));
            int bookId = Integer.parseInt(req.getParameter("bookId"));
            BookDao dao = new BookDao();
            boolean result=false;
            try {
                result=dao.deleteBookById(bookId,shopId);
            }catch (SQLException e){
                e.printStackTrace();
            }
            if (result) {
                resp.getWriter().print(JsonUtils.result2Json("1"));
            } else
                resp.getWriter().print(JsonUtils.result2Json("0"));

        }
        if (method.equals("deleteBatch")){
            String data=req.getParameter("data");
            String[] list=data.split(",");
            BookDao dao=new BookDao();
            if (dao.deleteBooksById(list)){
                resp.getWriter().print(JsonUtils.result2Json("1"));
            }else {
                resp.getWriter().print(JsonUtils.result2Json("0"));
            }
        }
    }
}
